local TIME_INDEX = GameInfo.Resources['RESOURCE_KURUMI_TIME'].Index;
function KurumiUnitKilledInCombat (killedPlayerId, killedUnitId, playerId, unitId)
	local playerConfig = PlayerConfigurations[playerId];
	local civ = playerConfig:GetCivilizationTypeName();
	if not ExposedMembers.DLHD.Utils.CivilizationHasTrait(civ, 'TRAIT_CIVILIZATION_ZAFKIEL') then
		return;
	end
	local player = Players[playerId];
	local amount = GlobalParameters.KURUMI_TIME_ON_KILL or 0;
	player:GetResources():ChangeResourceAmount(TIME_INDEX, amount);
end
Events.UnitKilledInCombat.Add(KurumiUnitKilledInCombat);

local PROJECT_KURUMI_HET_INDEX = GameInfo.Projects['PROJECT_KURUMI_HET'].Index;
local PROJECT_KURUMI_YOD_BET_INDEX = GameInfo.Projects['PROJECT_KURUMI_YOD_BET'].Index;
function KurumiCityProjectCompleted (playerId, cityId, projectId, buildngId, x, y, cancelled)
	if projectId == PROJECT_KURUMI_HET_INDEX then
		local city = CityManager.GetCity(playerId, cityId);
		local player = Players[playerId];
		local amount = GlobalParameters.KURUMI_TIME_PROJECT or 0;
		if city:GetPopulation() > 1 then
			city:ChangePopulation(-1);
			player:GetResources():ChangeResourceAmount(TIME_INDEX, amount);
		end
	end
	if projectId == PROJECT_KURUMI_YOD_BET_INDEX then
		local player = Players[playerId];
		for _, unit in player:GetUnits():Members() do
			UnitManager.RestoreUnitAttacks(unit);
			UnitManager.RestoreMovement(unit);
		end
	end
end
Events.CityProjectCompleted.Add(KurumiCityProjectCompleted);

function KurumiUnitKilledInCombat (killedPlayerId, killedUnitId, playerId, unitId)
	local killingUnit = UnitManager.GetUnit(playerId, unitId);
	local promotion = GameInfo.UnitPromotions['PROMOTION_SHADOW_L2'];
	if promotion == nil then
		return;
	end;
	if not killingUnit:GetExperience():HasPromotion(promotion.Index) then
		return;
	end
	local player = Players[playerId];
	local location = killingUnit:GetLocation();
	local x = location.x;
	local y = location.y;
	local damage = 30;
	for direction = 0, 5 do
		local plot = Map.GetAdjacentPlot(x, y, direction);
		if plot then
			for unit in Map.GetUnitsAt(plot):Units() do
				local owner = unit:GetOwner();
				if player:GetDiplomacy():IsAtWarWith(owner) then
					local unitInfo = GameInfo.Units[unit:GetType()];
					if (unitInfo.FormationClass == 'FORMATION_CLASS_LAND_COMBAT') or (unitInfo.FormationClass == 'FORMATION_CLASS_NAVAL') or (unitInfo.FormationClass == 'FORMATION_CLASS_AIR') then
						unit:ChangeDamage(damage);
					end
				end
			end
		end
	end
end
Events.UnitKilledInCombat.Add(KurumiUnitKilledInCombat);
function KurumiUnitKilledInCombat2 (killedPlayerId, killedUnitId, playerId, unitId)
	local killingUnit = UnitManager.GetUnit(playerId, unitId);
	local promotion = GameInfo.UnitPromotions['PROMOTION_SHADOW_R2'];
	if promotion == nil then
		return;
	end;
	if not killingUnit:GetExperience():HasPromotion(promotion.Index) then
		return;
	end
	local player = Players[playerId];
	player:GetResources():ChangeResourceAmount(TIME_INDEX, 2);
end
Events.UnitKilledInCombat.Add(KurumiUnitKilledInCombat2);

function HD_Kurumi_Aleph (playerId, unitId)
	local player = Players[playerId];
	local amount = 3;
	if player:GetResources():GetResourceAmount(TIME_INDEX) >= amount then
		local unit = UnitManager.GetUnit(playerId, unitId);
		player:GetResources():ChangeResourceAmount(TIME_INDEX, -amount);
		UnitManager.RestoreMovement(unit);
	end
end
GameEvents.HD_Kurumi_Aleph.Add(HD_Kurumi_Aleph);

local KURUMI_BET_KEY = 'KURUMI_BET';
function HD_Kurumi_Bet (playerId, unitId)
	local player = Players[playerId];
	local amount = 2;
	if player:GetResources():GetResourceAmount(TIME_INDEX) >= amount then
		local unit = UnitManager.GetUnit(playerId, unitId);
		player:GetResources():ChangeResourceAmount(TIME_INDEX, -amount);
		for direction = 0, 5 do
			local plot = Map.GetAdjacentPlot(unit:GetX(), unit:GetY(), direction);
			if plot then
				for unit in Map.GetUnitsAt(plot):Units() do
					local owner = unit:GetOwner();
					if player:GetDiplomacy():IsAtWarWith(owner) then
						print("Kurumi Bet Unit");
						local current = unit:GetProperty(KURUMI_BET_KEY) or 0;
						unit:SetProperty(KURUMI_BET_KEY, current + 1);
					end
				end
			end
		end
	end
end
GameEvents.HD_Kurumi_Bet.Add(HD_Kurumi_Bet);
function KurumiBetPlayerTurnStartComplete (playerId)
	local player = Players[playerId];
	for _, unit in player:GetUnits():Members() do
		local current = unit:GetProperty(KURUMI_BET_KEY);
		if current ~= nil then
			unit:ChangeMovesRemaining(-current);
			unit:SetProperty(KURUMI_BET_KEY, 0);
		end
	end
end
GameEvents.PlayerTurnStartComplete.Add(KurumiBetPlayerTurnStartComplete);

function HD_Kurumi_Gimel (playerId, unitId)
	local player = Players[playerId];
	local amount = 4;
	if player:GetResources():GetResourceAmount(TIME_INDEX) >= amount then
		local unit = UnitManager.GetUnit(playerId, unitId);
		player:GetResources():ChangeResourceAmount(TIME_INDEX, -amount);
		unit:GetExperience():ChangeExperience(15);
	end
end
GameEvents.HD_Kurumi_Gimel.Add(HD_Kurumi_Gimel);

function HD_Kurumi_Dalet (playerId, unitId)
	local player = Players[playerId];
	local amount = 4;
	if player:GetResources():GetResourceAmount(TIME_INDEX) >= amount then
		local unit = UnitManager.GetUnit(playerId, unitId);
		player:GetResources():ChangeResourceAmount(TIME_INDEX, -amount);
		unit:ChangeDamage(-100);
	end
end
GameEvents.HD_Kurumi_Dalet.Add(HD_Kurumi_Dalet);

local KURUMI_ZAYIN_KEY = 'KURUMI_ZAYIN';
function HD_Kurumi_Zayin (playerId, unitId)
	local player = Players[playerId];
	local amount = 9;
	if player:GetResources():GetResourceAmount(TIME_INDEX) >= amount then
		local unit = UnitManager.GetUnit(playerId, unitId);
		player:GetResources():ChangeResourceAmount(TIME_INDEX, -amount);
		unit:SetProperty(KURUMI_ZAYIN_KEY, 1);
	end
end
GameEvents.HD_Kurumi_Zayin.Add(HD_Kurumi_Zayin);
local SHADOW_L4_INDEX = GameInfo.UnitPromotions['PROMOTION_SHADOW_L4'].Index;
local SHADOW_L4_TURN_KEY = 'SHADOW_L4_TURN';
function KurumiCombat (combatResult)
	local attacker = combatResult[CombatResultParameters.ATTACKER][CombatResultParameters.ID];
	local attackerUnit = UnitManager.GetUnit(attacker.player, attacker.id);
	local defender = combatResult[CombatResultParameters.DEFENDER][CombatResultParameters.ID];
	local defenderUnit = UnitManager.GetUnit(defender.player, defender.id);
	if (attackerUnit ~= nil) and (attackerUnit:GetProperty(KURUMI_ZAYIN_KEY) ~= nil) and (attackerUnit:GetProperty(KURUMI_ZAYIN_KEY) ~= 0) then
		attackerUnit:SetProperty(KURUMI_ZAYIN_KEY, 0);
		UnitManager.Kill(defenderUnit);
	end
	if attackerUnit:GetExperience():HasPromotion(SHADOW_L4_INDEX) then
		local turn = Game.GetCurrentGameTurn();
		if attackerUnit:GetProperty(SHADOW_L4_TURN_KEY .. '_' .. turn) == nil then
			attackerUnit:SetProperty(SHADOW_L4_TURN_KEY .. '_' .. turn, 1);
            attackerUnit:ChangeDamage(-combatResult[CombatResultParameters.ATTACKER][CombatResultParameters.DAMAGE_TO]);
			local location = attackerUnit:GetLocation();
            Game.AddWorldViewText(0, Locale.Lookup("LOC_ABILITY_BLOCK_FIRST_NON_LETHAL_ATTACK_EACH_TURN_POP"), location.x, location.y);
		end
	end
	if defenderUnit:GetExperience():HasPromotion(SHADOW_L4_INDEX) then
		local turn = Game.GetCurrentGameTurn();
		if defenderUnit:GetProperty(SHADOW_L4_TURN_KEY .. '_' .. turn) == nil then
			defenderUnit:SetProperty(SHADOW_L4_TURN_KEY .. '_' .. turn, 1);
            defenderUnit:ChangeDamage(-combatResult[CombatResultParameters.DEFENDER][CombatResultParameters.DAMAGE_TO]);
			local location = defenderUnit:GetLocation();
            Game.AddWorldViewText(0, Locale.Lookup("LOC_ABILITY_BLOCK_FIRST_NON_LETHAL_ATTACK_EACH_TURN_POP"), location.x, location.y);
		end
	end
end
Events.Combat.Add(KurumiCombat);

local NIGHTMARE_INDEX = GameInfo.Districts['DISTRICT_KURUMI_NIGHTMARE_IKANDA'].Index;
local PALACE_INDEX = GameInfo.Buildings['BUILDING_PALACE'].Index;
function KurumiOnDistrictConstructed (playerId, districtType, x, y)
	if districtType == NIGHTMARE_INDEX then
		local vis = PlayerVisibilityManager.GetPlayerVisibility(playerId);
		local hiddenPlots = {};
		local availablePlots = {};
		for _, player in ipairs(Players) do
			if player:IsMajor() then
				for _, city in player:GetCities():Members() do
					local x = city:GetX();
					local y = city:GetY();
					if city:GetBuildings():HasBuilding(PALACE_INDEX) then
						local visType = vis:GetState(x, y);
						if visType == RevealedState.HIDDEN then
							table.insert(hiddenPlots, {X = x, Y = y});
						elseif visType == RevealedState.REVEALED then
							table.insert(availablePlots, {X = x, Y = y});
						end
					end
				end
			end
		end
		local x = -1;
		local y = -1;
		if #hiddenPlots > 0 then
			local rand = Game.GetRandNum(#hiddenPlots) + 1;
			x = hiddenPlots[rand].X;
			y = hiddenPlots[rand].Y;
		elseif #availablePlots > 0 then
			local rand = Game.GetRandNum(#availablePlots) + 1;
			x = availablePlots[rand].X;
			y = availablePlots[rand].Y;
		end
		if (x ~= -1) and (y ~= -1) then
			local plot = Map.GetPlot(x, y);
			vis:ChangeVisibilityCount(plot:GetIndex(), RevealedState.VISIBLE);
		end
	end
end
GameEvents.OnDistrictConstructed.Add(KurumiOnDistrictConstructed);

GameEvents.KurumiProductionSwitch.Add (function (playerId, cityId, amount)
	local city = CityManager.GetCity(playerId, cityId);
	city:GetBuildQueue():AddProgress(amount);
end);
GameEvents.KurumiScienceSwitch.Add (function (playerId, amount)
	local player = Players[playerId];
	player:GetTechs():ChangeCurrentResearchProgress(amount);
end);
GameEvents.KurumiCultureSwitch.Add (function (playerId, amount)
	local player = Players[playerId];
	player:GetCulture():ChangeCurrentCulturalProgress(amount);
end);
GameEvents.KurumiGoldSwitch.Add (function (playerId, amount)
	local player = Players[playerId];
	player:GetTreasury():ChangeGoldBalance(amount);
end);
GameEvents.KurumiFaithSwitch.Add (function (playerId, amount)
	local player = Players[playerId];
	player:GetReligion():ChangeFaithBalance(amount);
end);